package com.future.lock.me.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.utils.EventBusUtil;
import com.future.lock.R;
import com.future.lock.common.MyApp;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.mall.entity.beans.PayInfo;
import com.future.lock.mall.entity.response.BaseDataResponse;
import com.future.lock.mall.events.Events;
import com.future.lock.mall.tasks.SetOrderStatusTask;
import com.future.lock.me.order.adapter.OrderInfoListAdapter;
import com.future.lock.me.order.entity.bean.OrderListInfoBean;
import com.future.lock.me.order.entity.response.OrderListInfoResponse;
import com.future.lock.pay.PayActivity;
import com.yzh.modaldialog.dialog.impl.SelectorDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrderListActivity extends PayActivity {

    public static final String ORDER_TYPE = "order_type";
    final int DEFAULT_LIST_PADDING_IN_PX = 30;

    @BindView(R.id.orderRecyclerView)
    RecyclerView orderRecyclerView;

    OrderInfoListAdapter adapter;

    // default is for all
    int status = OrderListInfoBean.ORDER_STATUS_NONE;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_list);
        ButterKnife.bind(this);
        if (!EventBus.getDefault()
                .isRegistered(this)) {
            EventBusUtil.register(this);
        }
    }

    @Override
    protected void initView() {
        setTitle("我的订单");
        this.adapter = new OrderInfoListAdapter(R.layout.item_order_info, new ArrayList<OrderListInfoBean>());
        this.orderRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        this.orderRecyclerView.setAdapter(this.adapter);
        //空视图
        View emptyView = getLayoutInflater().inflate(R.layout.layout_default_empty, null);
        ((TextView) emptyView.findViewById(R.id.tv_tib)).setText("暂无订单");
        adapter.setEmptyView(emptyView);
        //点击事件
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(OrderListActivity.this, OrderDetailsActivity.class);
                intent.putExtra(OrderDetailsActivity.ORDER_ID,
                        OrderListActivity.this.adapter.getData()
                                .get(position)
                                .getOrder_id());
                startActivity(intent);
            }
        });
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            if (view.getId() == R.id.operateButton) {
                OrderListInfoBean bean = adapter.getData()
                        .get(position);
                if (bean.isWaitToPay()) {
                    tryToPayOrder(bean.getOrder_id());
                }
                else if (bean.isWaitForDelivery()) {
                    tryToConfirmDelivery(bean.getOrder_id());
                }
            }
        });

        refreshAdapter();
    }

    @Override
    protected void initLogic() {

    }

    /**
     * refresh adapter
     */
    protected void refreshAdapter() {
        Callback<String> callback = new Callback<String>() {

            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                OrderListInfoResponse orderInfoResponse = new OrderListInfoResponse();
                orderInfoResponse.parse(response.body());
                if (orderInfoResponse.success == 1) {
                    adapter.setNewData(orderInfoResponse.data);
                }
                else {
                    toast(orderInfoResponse.msg);
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                toast(t.getMessage());
            }
        };


        // 是否取得所有数据
        if (this.status == OrderListInfoBean.ORDER_STATUS_NONE) {
            HttpUtils.getHttpApi()
                    .getAllOrderList(MyApp.getUserToken())
                    .enqueue(callback);
        }
        else {
            HttpUtils.getHttpApi()
                    .getOrderList(MyApp.getUserToken(), this.status)
                    .enqueue(callback);
        }
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        this.status = extras != null ? extras.getInt(OrderListActivity.ORDER_TYPE) : this.status;
    }

    private void tryToPayOrder(String order_id) {
        showLoadingDialog();
        HttpUtils.getHttpApi()
                .getPayInfo(MyApp.getUserToken(), order_id)
                .enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        dissmissLoadingDialog();
                        BaseDataResponse<PayInfo> response1 = new BaseDataResponse<PayInfo>(PayInfo.class);
                        response1.parse(response.body());
                        if (response1.data != null) {
                            if (response1.data.getPay_type() == 0) {
                                payAli(response1.data.getAlipay_info()
                                                .getTotal_amount(),
                                        response1.data.getAlipay_info()
                                                .getSubject(),
                                        response1.data.getAlipay_info()
                                                .getOrder_sn());
                            }
                            else {
                                payWechat(response1.data.getWxPayJson());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        dissmissLoadingDialog();
                        toast("获取订单支付信息失败, 请稍后再试!");
                    }
                });
    }

    private void tryToConfirmDelivery(String orderId) {
        final int choice = new SelectorDialog(this, R.layout.dialog_default) {
            @Override
            protected void onDialogCreate(Dialog dialog, Bundle savedInstanceState) {
                setGravity(Gravity.CENTER);
                super.onDialogCreate(dialog, savedInstanceState);
                ((TextView) dialog.findViewById(R.id.tv_message)).setText("确认已经收到货了吗？");
                ((TextView) dialog.findViewById(R.id.btn_cancel)).setText("取消");
                ((TextView) dialog.findViewById(R.id.btn_ok)).setText("确认");
            }
        }.doModal();

        if (choice == R.id.btn_ok) {
            SetOrderStatusTask.setOrderStatus(MyApp.getUserToken(), orderId, SetOrderStatusTask.STATUS_CONFIRMED, () -> {
                toast("成功确认收货!");
                refreshAdapter();
            }, () -> toast("确认收货失败, 请稍后再试!"));
        }
    }

    @Override
    public void paySuccess() {
        toast("支付成功!");
        refreshAdapter();
    }

    @Override
    public void payFail() {
        toast("支付失败或取消!");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault()
                .isRegistered(this)) {
            EventBusUtil.unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderStatusUpdateEvent(Events.OnOrderStatusUpdateEvent onOrderStatusUpdateEvent) {
        refreshAdapter();
    }
}
